// localLifePackage/pages/localLiving/localLiving.js
var app = getApp();

var common = require("../../../common/common.js").common;

Page({
    /**
   * 页面的初始数据
   */
    data: {
        moduleLiving: [ {
            id: 1,
            value: "1",
            name: "到店自提",
            checked: false
        }, {
            id: 2,
            value: "2",
            name: "商家配送",
            checked: false
        } ],
        step: 1,
        //步骤
        name: "",
        contacts: "",
        phone: "",
        address: "",
        addressName: "",
        latitude: "",
        longitude: "",
        detail_address: "",
        start_time: "",
        end_time: "",
        remark: "",
        moduleLiving_checked: false,
        moduleTeam_checked: false,
        photo_image: [ {
            name: "front_card",
            text: "身份证正面照",
            id: "",
            url: ""
        }, {
            name: "reverse_card",
            text: "身份证反面照",
            id: "",
            url: ""
        }, {
            name: "license_card",
            text: "营业执照",
            id: "",
            url: ""
        }, {
            name: "store_card",
            text: "店内照片",
            id: "",
            url: ""
        } ],
        tmplIds: [],
        subscribeMessage: true
    },
    /**
   * 生命周期函数--监听页面加载
   */
    onLoad: function(options) {
        var that = this;
        if (options.status == 1) {
            that.setData({
                status: options.status ? options.status : "0"
            });
        } else {
            wx.showModal({
                title: "提示",
                content: "该小程序无此功能!",
                showCancel: false,
                success(res) {
                    wx.navigateBack({});
                    return;
                }
            });
        }
        //首次直接进入，拿user_id
                if (app.globalData.user) {
            //如果直接拿到openid
            that.setData({
                uid: app.globalData.user.uid
            });
        } else {
            //回调拿到openid
            app.userInfoReadyCallback = (res => {
                that.setData({
                    uid: res.uid
                });
            });
        }
        //获取模板消息
                this.getTempIds();
        //获取本地经纬度
        // wx.getLocation({
        //   type: 'wgs84',
        //   success(res) {
        //     console.log(res);
        //     that.setData({
        //       latitude: res.latitude,
        //       longitude: res.longitude
        //     })
        //   }
        // })
        },
    /**
   * 生命周期函数--监听页面初次渲染完成
   */
    onReady: function() {},
    /**
   * 生命周期函数--监听页面显示
   */
    onShow: function() {},
    /**
   * 生命周期函数--监听页面隐藏
   */
    onHide: function() {},
    /**
   * 生命周期函数--监听页面卸载
   */
    onUnload: function() {},
    /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
    onPullDownRefresh: function() {},
    /**
   * 页面上拉触底事件的处理函数
   */
    onReachBottom: function() {},
    /**
   * 用户点击右上角分享
   */
    onShareAppMessage: function() {},
    chooseAddress: function() {
        let that = this;
        wx.chooseLocation({
            success(res) {
                that.setData({
                    detail_address: res.name,
                    latitude: res.latitude,
                    longitude: res.longitude
                });
            },
            fail: function() {
                wx.getSetting({
                    success: function(res) {
                        var statu = res.authSetting;
                        if (!statu["scope.userLocation"]) {
                            wx.showModal({
                                title: "是否授权当前位置",
                                content: "需要获取您的地理位置，请确认授权，否则地图功能将无法使用",
                                success: function(tip) {
                                    if (tip.confirm) {
                                        wx.openSetting({
                                            success: function(data) {
                                                if (data.authSetting["scope.userLocation"] === true) {
                                                    wx.showToast({
                                                        title: "授权成功",
                                                        icon: "success",
                                                        duration: 1e3
                                                    });
                                                    //授权成功之后，再调用chooseLocation选择地方
                                                                                                        that.chooseAddress();
                                                } else {
                                                    wx.showToast({
                                                        title: "授权失败",
                                                        icon: "success",
                                                        duration: 1e3
                                                    });
                                                }
                                            }
                                        });
                                    }
                                }
                            });
                        }
                    },
                    fail: function(res) {
                        wx.showToast({
                            title: "调用授权窗口失败",
                            icon: "success",
                            duration: 1e3
                        });
                    }
                });
            }
        });
    },
    /** 
   * 记录 input 的值
   * e: object 
   */
    recordValue: function(e) {
        let key = e.currentTarget.dataset.name;
        let value = e.detail.value;
        console.log(key + "," + value);
        this.setData({
            [key]: value
        });
    },
    bindAllchange(e) {
        console.log("checkbox发生change事件，携带value值为：", e.detail.value);
        if (e.detail.value.length > 1) {
            this.setData({
                moduleLiving_checked: true
            });
        } else {
            this.setData({
                moduleLiving_checked: false
            });
        }
    },
    checkboxLivingChange(e) {
        console.log("checkbox发生change事件，携带value值为：", e.detail.value);
        let items = this.data.moduleLiving;
        if (e.detail.value == "生活商超") {
            items.forEach((item, index) => {
                item.checked = true;
            });
        } else {
            items.forEach((item, index) => {
                item.checked = false;
            });
        }
        this.setData({
            moduleLiving: items
        });
    },
    bindStartTimeChange: function(e) {
        console.log("picker发送选择改变，携带值为", e.detail.value);
        this.setData({
            start_time: e.detail.value
        });
    },
    bindEndTimeChange: function(e) {
        console.log("picker发送选择改变，携带值为", e.detail.value);
        this.setData({
            end_time: e.detail.value
        });
    },
    next: function() {
        let that = this;
        if (!that.data.name) {
            wx.showModal({
                title: "提示",
                content: "商家名称未输入！",
                showCancel: false
            });
            return;
        }
        if (!that.data.contacts) {
            wx.showModal({
                title: "提示",
                content: "联系人未输入！",
                showCancel: false
            });
            return;
        }
        if (!that.data.phone || !/^1[3456789]\d{9}$/.test(that.data.phone)) {
            wx.showModal({
                title: "提示",
                content: "请输入正确的手机号码！",
                showCancel: false
            });
            return;
        }
        if (!that.data.address) {
            wx.showModal({
                title: "提示",
                content: "商家地址未选择！",
                showCancel: false
            });
            return;
        }
        // if (!that.data.moduleTeam_checked){
        //   wx.showModal({
        //     title: '提示',
        //     content: '请选择模式为团购活动!',
        //     showCancel: false,
        //   })
        //   return;
        // }
                if (!that.data.detail_address) {
            wx.showModal({
                title: "提示",
                content: "商家地址未选择！",
                showCancel: false
            });
            return;
        }
        if (!that.data.start_time || !that.data.end_time) {
            wx.showModal({
                title: "提示",
                content: "请选择营业的起始时间！",
                showCancel: false
            });
            return;
        }
        this.setData({
            step: 2
        });
    },
    chooseImage: function(e) {
        let that = this;
        let index = e.currentTarget.dataset.index;
        let name = e.currentTarget.dataset.name;
        let cw = "photo_image[" + index + "].url";
        let wId = "photo_image[" + index + "].id";
        wx.chooseImage({
            count: 1,
            sizeType: [ "original", "compressed" ],
            sourceType: [ "album", "camera" ],
            success(res) {
                // tempFilePath可以作为img标签的src属性显示图片
                const tempFilePaths = res.tempFilePaths;
                that.uploadFile(tempFilePaths, cw, wId);
                // that.setData({
                //   [cw]: tempFilePaths[0]
                // })
                        }
        });
    },
    uploadFile: function(file, cw, wId) {
        var that = this;
        let domain = app.globalData.domain.split("frontend")[0] + "backend" + app.globalData.domain.split("frontend")[1];
        wx.uploadFile({
            url: domain + "Imagesystem/img/saveimg",
            //仅为示例，非真实的接口地址
            filePath: file[0],
            name: "file",
            formData: {
                uniacid: wx.getStorageSync("uniacid"),
                esb: 3,
                img_type: "full"
            },
            header: {
                "Content-Type": "multipart/form-data",
                uniacid: wx.getStorageSync("uniacid")
            },
            success(res) {
                let data = JSON.parse(res.data);
                that.setData({
                    [cw]: data.extra.image[0].url,
                    [wId]: data.extra.image[0].id
                });
            },
            fail: function(res) {
                wx.hideToast();
                wx.showModal({
                    title: "错误提示",
                    content: "上传图片失败",
                    showCancel: false,
                    success: function(res) {}
                });
            }
        });
    },
    create: function() {
        let that = this;
        that.create_ch();
        if (that.data.subscribeMessage) {
            wx.requestSubscribeMessage({
                tmplIds: that.data.tmplIds,
                success(res) {},
                fail(err) {
                    console.log(err);
                }
            });
        }
    },
    create_ch: function() {
        let that = this;
        let flag = that.data.photo_image.every(function(obj) {
            return !obj.url;
        });
        if (flag) {
            wx.showModal({
                title: "提示",
                content: "相关照片未上传完成！",
                showCancel: false
            });
            return;
        }
        let business_qualifications = [];
        that.data.photo_image.forEach(function(item, i) {
            if (item.url) {
                business_qualifications.push(item.id);
            }
        });
        let delivery_arr = [];
        that.data.moduleLiving.forEach((item, index) => {
            delivery_arr.push(item.value);
        });
        let delivery = delivery_arr.join(",");
        let open_module = "";
        if (that.data.moduleTeam_checked && delivery_arr.length < 1) {
            open_module = 2;
        }
        if (!that.data.moduleTeam_checked && delivery_arr.length > 0) {
            open_module = 4;
        }
        if (that.data.moduleTeam_checked && delivery_arr.length > 0) {
            open_module = 6;
        }
        common.request({
            endpoint: "Localbusiness/merchant/merchant-create",
            method: "post",
            data: {
                user_id: that.data.uid,
                name: that.data.name,
                contact: that.data.contacts,
                phone: that.data.phone,
                address: that.data.address + "," + that.data.detail_address,
                start_time: that.data.start_time,
                end_time: that.data.end_time,
                open_module: open_module,
                remark: that.data.remark,
                business_qualifications: business_qualifications.join(","),
                position: that.data.longitude + "," + that.data.latitude,
                delivery: delivery
            },
            success: res => {
                if (res.code == 0) {
                    wx.showModal({
                        title: "提示",
                        content: "本地商家已入驻，请等待管理员审核",
                        showCancel: false,
                        success(res) {
                            wx.switchTab({
                                url: "/pages/personal/personal"
                            });
                        }
                    });
                } else {
                    wx.showModal({
                        title: "提示",
                        content: res.message,
                        showCancel: false
                    });
                }
            },
            fail(err) {
                wx.showModal({
                    title: "提示",
                    content: err.message,
                    showCancel: false
                });
            }
        });
    },
    bindRegionChange: function(e) {
        console.log("picker发送选择改变，携带值为", e.detail.value);
        this.setData({
            address: e.detail.code[0].slice(0, 2) + "," + e.detail.code[1].slice(0, 4) + "," + e.detail.code[2],
            addressName: e.detail.value[0] + "-" + e.detail.value[1] + "-" + e.detail.value[2]
        });
    },
    checkboxChange: function(e) {
        let that = this;
        console.log("checkbox发生change事件，携带value值为：", e.detail.value);
        if (e.detail.value == "团购活动") {
            that.setData({
                moduleTeam_checked: true
            });
        } else {
            that.setData({
                moduleTeam_checked: false
            });
        }
    },
    //获取tempIds
    getTempIds: function() {
        var that = this;
        common.request({
            endpoint: "set/template_get",
            method: "post",
            data: {},
            header: {
                "content-type": "application/json"
            },
            success: res => {
                console.log(res);
                let tmplIds = [];
                let subscribeMessage = true;
                res.extra.map(v => {
                    if (v.type == "32" && v.status == "1") {
                        tmplIds.push(v.template_id);
                    }
                });
                if (!tmplIds.length) {
                    subscribeMessage = false;
                }
                that.setData({
                    tmplIds: tmplIds,
                    subscribeMessage: subscribeMessage
                });
            }
        });
    }
});